package com.quick.threadtest;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;

public class BlockingQueueTest {
    public static void main(String[] args) throws Exception{
        ArrayBlockingQueue<Integer> arrayBlockingQueue = new ArrayBlockingQueue(8);
        for (int i = 0; i < 30; i++) {
            Thread thread = new Thread(new putTest(arrayBlockingQueue,i,"ArrayBlockingQueue"));
            thread.start();
        }
        for (int i = 0; i < 30; i++) {
            Thread thread = new Thread(new taskTest(arrayBlockingQueue));
            thread.start();
        }

        System.out.println("====================");

        LinkedBlockingQueue<Integer> linkedBlockingQueue = new LinkedBlockingQueue<Integer>(8);
        for (int i = 0; i < 30; i++) {
            Thread thread = new Thread(new putTest(linkedBlockingQueue,i,"LinkedBlockingQueue"));
            thread.start();
        }
        for (int i = 0; i < 30; i++) {
            Thread thread = new Thread(new taskTest(linkedBlockingQueue));
            thread.start();
        }
        System.out.println("====================");

        SynchronousQueue<Integer> synchronousQueue = new SynchronousQueue<Integer>();
        for (int i = 0; i < 30; i++) {
            Thread thread = new Thread(new putTest(synchronousQueue,i,"SynchronousQueue"));
            thread.start();
        }
        for (int i = 0; i < 30; i++) {
            Thread thread = new Thread(new taskTest(synchronousQueue));
            thread.start();
        }
    }



}

class putTest implements Runnable{
    private BlockingQueue blockingQueue;
    private int a;
    private String name;
    public putTest(BlockingQueue blockingQueue,int a,String name){
        this.blockingQueue = blockingQueue;
        this.a = a;
        this.name = name;
    }
    @Override
    public void run() {
        try {
            blockingQueue.put(a);
            System.out.println(name+"---put---size--"+blockingQueue.size());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
class taskTest implements Runnable{
    private BlockingQueue blockingQueue;
    public taskTest(BlockingQueue blockingQueue){
        this.blockingQueue = blockingQueue;
    }
    @Override
    public void run() {
        try {
            System.out.println("task--size--"+blockingQueue.size());
            System.out.println("task="+blockingQueue.take());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
